package com.bosssoft.trainee.rbac.filter;

import com.bosssoft.trainee.rbac.entity.dto.UserDTO;
import com.bosssoft.trainee.rbac.entity.vo.UsersVO;
import org.springframework.beans.BeanUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "UserLogin",urlPatterns = "/user/*")
public class UserLogin implements Filter {
    private static final String LOGIN = "login";
    private static final String USER_LOGIN = "user/Login";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取用户访问的URI
        HttpServletRequest req = (HttpServletRequest)request;
        String uri = req.getRequestURI();

        //判断当前访问的URI是否是用户登录资源，如果是则放行
        if(uri.contains(LOGIN)  || uri.contains(USER_LOGIN) ){
            chain.doFilter(req, response);
        }else{
            //用户是否登录的判断
            HttpSession session = req.getSession();
            UsersVO userVO = (UsersVO)session.getAttribute("user");
            UserDTO usersDTO = new UserDTO();
            BeanUtils.copyProperties(userVO,usersDTO);
            if(usersDTO.getUsername().length() > 0){
                chain.doFilter(req, response);
            }else{
                req.setAttribute("msg", "请登录");
                req.getRequestDispatcher("/login").forward(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
